package com.dlc.beijingrfid.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.dlc.commonlibrary.adapter.AdapterScanner;
import com.dlc.commonlibrary.ble.ClassScanner;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.net.bean.OrderDetailBean;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import zpSDK.zpSDK.zpBluetoothPrinter;

public class PrintActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.button_BT_search)
    Button btn_search;
    @BindView(R.id.lv_BT_paired)
    ListView DeviceListView;
    private final String TAG = "connected_check";
    @BindView(R.id.button_BT_print)
    Button mButtonBTPrint;
    private BluetoothAdapter mBTadapter;
    private Set<BluetoothDevice> mBTpaired;

    private ArrayList<ClassScanner> DeviceList;
    private AdapterScanner ListAdapter;
    String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
    public String mLast_addr = "";
    private zpBluetoothPrinter zpSDK;
    private OrderDetailBean orderDetailBean;
    @Override
    protected int getLayoutID() {
        return R.layout.activity_print;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        int type = bundle.getInt("type");
         orderDetailBean = (OrderDetailBean) bundle.getSerializable("detailData");

        initReceiver();
        mBTadapter = BluetoothAdapter.getDefaultAdapter();
        DeviceListView.setOnItemLongClickListener(mDeviceLongClickListener);
        DeviceListView.setOnItemClickListener(mDeviceClickListener);
        btn_search.setOnClickListener(this);
        mButtonBTPrint.setOnClickListener(this);
        PairedListUpdate("");
        discovery_start();
        zpSDK=new zpBluetoothPrinter(this);
    }

    private void initReceiver() {
        IntentFilter action_found = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        getActivity().registerReceiver(mReceiver, action_found);

       // IntentFilter action_bond = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        //getActivity().registerReceiver(mReceiver, action_bond);

        IntentFilter action_disconnected =
            new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        getActivity().registerReceiver(mReceiver, action_disconnected);

        IntentFilter action_discover_end =
            new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        getActivity().registerReceiver(mReceiver, action_discover_end);

        IntentFilter action_pairing_request = new IntentFilter(ACTION_PAIRING_REQUEST);
        getActivity().registerReceiver(mReceiver, action_pairing_request);
    }

    public void PairedListUpdate(String last_addr) {
        mBTpaired = mBTadapter.getBondedDevices();
        DeviceList = new ArrayList<ClassScanner>();
        for (BluetoothDevice btd : mBTpaired) {
            int icon = (btd.getAddress().equals(last_addr)) ? R.drawable.ic_action_save
                : R.drawable.ic_action_bluetooth;
            //addDevice(btd, icon);
        }
        ListAdapter = new AdapterScanner(getActivity(), DeviceList);
        DeviceListView.setAdapter(ListAdapter);
    }

    private void addDevice(BluetoothDevice btd, int type) {
        if (btd.getName() == null) return;

        String name = btd.getName().toUpperCase();
        int index = 0;

        for (index = 0; index < DeviceList.size(); index++) {
            ClassScanner temp = DeviceList.get(index);
            if (temp.getName().equals(btd.getName())) break;
        }

        if (index != DeviceList.size()) return;

        if (name.startsWith("CS3")&&!name.endsWith("L")) {
            DeviceList.add(new ClassScanner(R.drawable.a100, type, btd));
        }
    }

    public void setConnectedScanner(String last_addr) {
        int index = 0;
        int selectedIndex = -1;

        for (index = 0; index < DeviceList.size(); index++) {
            ClassScanner temp = DeviceList.get(index);
            temp.setDisConnected(last_addr);
            if (temp.getMac().equals(last_addr)) selectedIndex = index;
        }

        if (index != DeviceList.size()) return;

        ClassScanner connected = DeviceList.get(selectedIndex);
        connected.setConnected();
        getActivity().runOnUiThread(updateListTable);
    }

    public void setDisconnected(String last_addr) {
        int index = 0;

        for (index = 0; index < DeviceList.size(); index++) {
            ClassScanner temp = DeviceList.get(index);
            temp.setDisConnected(last_addr);
        }
        getActivity().runOnUiThread(updateListTable);
    }

    public void pairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass().getMethod("createBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            Log.e("dsm362-pairDevice", e.getMessage());
        }


		/*
		String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
        Intent intent = new Intent(ACTION_PAIRING_REQUEST);
        String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
        intent.putExtra(EXTRA_DEVICE, device);
        String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT";
        int PAIRING_VARIANT_PIN = 1234;
        intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getActivity().startActivityForResult(intent,0);
        */
    }

    private void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass().getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            Log.e("dsm362-unpairDevice", e.getMessage());
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

	      /*  if(LocationClient.hasError(intent)) {
	        	int errorCode = LocationClient.getErrorCode(intent);
	            Log.e("dsm362", "Location Services error: " + Integer.toString(errorCode));
	            return;
	        }*/
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                // Add the name and address to an array adapter to show in a ListView
                addDevice(device, R.drawable.ic_action_new);
                getActivity().runOnUiThread(updateListTable);
            } else if (ACTION_PAIRING_REQUEST.equals(action)) {
               // setBluetoothPairingPin(device);
            }
            // When the device bond state changed.
            else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                int prevBondState =
                    intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
                int bondState =
                    intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);

                if (bondState == BluetoothDevice.BOND_BONDING) {
                    Log.i("dsm362", "BOND_BONDING");
                    pairDevice(device);
                } else if (bondState == BluetoothDevice.BOND_BONDED) {
                    Log.i("dsm362", "BOND_BONDED");
                } else if (bondState == BluetoothDevice.BOND_NONE) {
                    Log.i("dsm362", "BOND_NONE");
                } else if (bondState == BluetoothDevice.ERROR) {
                    Log.i("dsm362", "ERROR");
                }

                if (prevBondState == BluetoothDevice.BOND_BONDED
                    && bondState == BluetoothDevice.BOND_NONE) {
                    //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    //pairDevice(device);
                    //Log.i("dsm362", "pair start");
                } else if (prevBondState == BluetoothDevice.BOND_BONDING
                    && bondState == BluetoothDevice.BOND_BONDED) {
                    //BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    //Log.i("dsm362", "???");
                }
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                //MainActivity main_act = (MainActivity) getActivity();
                //main_act.ScannerDisconnectedEventHandler();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
               // Toast.makeText(getActivity(), "BT discovery finished", Toast.LENGTH_SHORT).show();
                if (discover_dialog != null) {
                    discover_dialog.cancel();
                    discover_dialog = null;
                }
            }
        }
    };

    public void setBluetoothPairingPin(BluetoothDevice device) {
        String string = "0000";

        byte[] pinBytes = string.getBytes();
        try {
            //Log.d(TAG, "Try to set the PIN");
            Method m = device.getClass().getMethod("setPin", byte[].class);
            m.invoke(device, pinBytes);
            Log.d("dsm362", "Success to add the PIN.");
            try {
                device.getClass()
                    .getMethod("setPairingConfirmation", boolean.class)
                    .invoke(device, true);
                Log.d("dsm362", "Success to setPairingConfirmation.");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //       Log.e(TAG, e.getMessage());
                e.printStackTrace();
            }
        } catch (Exception e) {
            //  Log.e(TAG, e.getMessage());
            e.printStackTrace();
        }
    }

    private ProgressDialog discover_dialog = null;

    public void discovery_start() {
        DeviceList.clear();
        ListAdapter.notifyDataSetChanged();
        if (mBTadapter.isDiscovering() == false) {
            mBTadapter.startDiscovery();
            discover_dialog = new ProgressDialog(getActivity());
            discover_dialog.setMessage("Finding Scanner...");
            discover_dialog.setButton(Dialog.BUTTON_NEGATIVE, "Stop",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mBTadapter.isDiscovering()) mBTadapter.cancelDiscovery();
                    }
                });
            discover_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            discover_dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (mBTadapter.isDiscovering()) mBTadapter.cancelDiscovery();
                }
            });
            discover_dialog.show();
        }
    }

    public Runnable updateListTable = new Runnable() {
        public void run() {
            PrintActivity.this.ListAdapter.notifyDataSetChanged();
        }
    };



    private AdapterView.OnItemClickListener mDeviceClickListener =
        new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final ClassScanner target = DeviceList.get(position);
                LogPlus.e("diz===="+target.getDevice().getAddress());
                zpSDK.connect(target.getDevice().getAddress());
                showWaitingDialog("正在连接",false);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissWaitingDialog();
                        if (zpSDK.isConnected()) {
                            ToastUtil.show(PrintActivity.this, "连接成功开始打印");
                            Print();
                        }else {
                            ToastUtil.show(PrintActivity.this, "连接失败");
                        }
                    }
                },3000);
            }
        };

    private AdapterView.OnItemLongClickListener mDeviceLongClickListener =
        new AdapterView.OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
                long id) {
                final int index = position;
                final ClassScanner target = DeviceList.get(index);

                AlertDialog.Builder alertDlg = new AlertDialog.Builder(view.getContext());
                alertDlg.setTitle("Scanner Remove");
                alertDlg.setMessage(
                    String.format("Do you want to remove %s in list? ", target.getName()));

                alertDlg.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        unpairDevice(target.getDevice());
                        DeviceList.remove(index);
                        getActivity().runOnUiThread(updateListTable);

                        dialog.dismiss();  // AlertDialog�� �ݴ´�.
                    }
                });

                alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();  // AlertDialog�� �ݴ´�.
                    }
                });
                alertDlg.show();

                return true;
            }
        };

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.button_BT_search) {
            //Toast.makeText(getActivity(), "OneFragment", Toast.LENGTH_SHORT).show();
            if (mBTadapter.isDiscovering() == false) discovery_start();
        } else if (v.getId() == R.id.button_BT_print) {
            //Toast.makeText(getActivity(), "OneFragment", Toast.LENGTH_SHORT).show();
            Print();
        }
    }

    /**
     * 打印数据
     */
    public void Print() {
        int line = 1;
        if (!zpSDK.isConnected()) {
            ToastUtil.show(this, "请先连接");
            return;
        }
        SimpleDateFormat formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd HH:mm");
        Date curDate =  new Date(System.currentTimeMillis());
        String   date   =   formatter.format(curDate);
        List<OrderDetailBean.DataBean.SpecGroupBean> mlist = orderDetailBean.data.spec_group;
        String orderno = orderDetailBean.data.orderno;
        String title;

        if (orderno.contains("W")) {
            title = "收洗单" ;
        } else if (orderno.contains("D")) {
            title = "送货单" ;
        } else  {
            title = "返洗单" ;
        }
        if (mlist.size() > 0) {
            zpSDK.pageSetup(568, (mlist.size()+15)*50);
            zpSDK.drawText(0,  50*line , "--------------------------------------------------------------", 3, 0, 0, false, false);
            line++;
            zpSDK.drawText(50,  50*line , "深圳医疗卫生专业服务中心", 3, 0, 0, false, false);
            line++;
            zpSDK.drawText(100, 50*line , "      "+title, 3, 0, 0, false, false);
            line++;
            zpSDK.drawText(50, 50*line , "单号："+orderDetailBean.data.orderno, 2, 0, 0, false, false);
            line++;
            zpSDK.drawText(30, 50*line , "总数量："+orderDetailBean.data.nums, 2, 0, 0, false, false);
            line++;
            zpSDK.drawText(8, 50*line, "医院科室："+orderDetailBean.data.hotel+orderDetailBean.data.office , 2, 0, 0, false, false);
            line++;
            zpSDK.drawText(55, 50*line, "日期："+date , 2, 0, 0, false, false);
            line++;
            String string = "";
            for (int i = 0; i < mlist.size(); i++) {
                OrderDetailBean.DataBean.SpecGroupBean bean = mlist.get(i);
                string = "分类规格：" + bean.spec ;
                zpSDK.drawText(10, 50*line, "产品名称：" + bean.title, 2, 0, 0, false, false);
                line++;
                zpSDK.drawText(10, 50*line, string, 2, 0, 0, false, false);
                line++;
                zpSDK.drawText(55, 50*line, "数量：" + bean.count, 2, 0, 0, false, false);
                line++;
            }
            zpSDK.drawText(10, 50*line, "                    " , 2, 0, 0, false, false);
            line++;
            zpSDK.drawText(55, 50*line, "签名：" , 2, 0, 0, false, false);
            line++;
            zpSDK.drawText(10, 50*line, "                    " , 2, 0, 0, false, false);
            line++;
            zpSDK.drawText(10, 50*line, "                    " , 2, 0, 0, false, false);
            line++;
            zpSDK.print(0, 0);
            zpSDK.disconnect();
        }
    }

    //public void ConnectTo(BluetoothDevice scanner) {
    //    // TODO Auto-generated method stub
    //    if(mA100 != null) {
    //        if(mA100.isConnected() == true) {
    //            mA100.stop();
    //        }
    //        mA100.connect(scanner);
    //    }
    //}
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiver);
    }
}
